<template>
  <div id="cesiumContainer"></div>
</template>

<script>
import { onMounted, onUnmounted, ref } from 'vue';
import * as Cesium from 'cesium';
import 'cesium/Build/Cesium/Widgets/widgets.css';

// 设置Cesium Ion的默认访问令牌
Cesium.Ion.defaultAccessToken = undefined;

export default {
  name: 'BaseCesiumViewer',
  props: {
    options: {
      type: Object,
      default: () => ({})
    }
  },
  emits: ['viewer-ready'],
  setup(props, { expose, emit }) {
    const viewer = ref(null);

    onMounted(async () => {
      // Create the imagery provider with error handling
      let imageryProvider;
      try {
        imageryProvider = new Cesium.TileMapServiceImageryProvider({
          url: '/assets/Textures/NaturalEarthII'
        });
        
        // Wait for the imagery provider to be ready
        await imageryProvider.readyPromise;
        console.log('Imagery provider loaded successfully');
      } catch (error) {
        console.warn('Failed to load local imagery provider, using default imagery:', error);
        imageryProvider = undefined; // Use Cesium's default imagery
      }

      const defaultOptions = {
        terrainProvider: new Cesium.EllipsoidTerrainProvider(),
        animation: false,
        timeline: false,
        vrButton: false,
        geocoder: false,
        homeButton: true,
        navigationHelpButton: false,
        scene3DOnly: false,
        baseLayerPicker: false,
        imageryProvider: imageryProvider
      };
      
      const viewerOptions = { ...defaultOptions, ...props.options };
      
      // 创建Cesium Viewer实例
      const cesiumViewer = new Cesium.Viewer('cesiumContainer', viewerOptions);
      viewer.value = cesiumViewer;
      
      // If imagery provider was not set in constructor due to error, set it after initialization
      if (!viewerOptions.imageryProvider) {
        try {
          const fallbackProvider = new Cesium.TileMapServiceImageryProvider({
            url: '/assets/Textures/NaturalEarthII'
          });
          await fallbackProvider.readyPromise;
          cesiumViewer.imageryLayers.addImageryProvider(fallbackProvider);
        } catch (error) {
          console.warn('Could not set imagery provider after initialization:', error);
        }
      }
      
      // Expose viewer instance and Cesium namespace to parent components
      expose({
        viewer: viewer.value,
        Cesium
      });
      
      // Emit event when viewer is ready
      emit('viewer-ready', {
        viewer: cesiumViewer,
        Cesium
      });
    });

    onUnmounted(() => {
      if (viewer.value) {
        viewer.value.destroy();
      }
    });

    return {
      viewer
    };
  }
};
</script>

<style scoped>
#cesiumContainer {
  width: 100%;
  height: 100vh;
  margin: 0;
  padding: 0;
  overflow: hidden;
}
</style>